package com.pclong.fightlandlordserver;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Random;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 *
 * @author long@7road.com
 * @Date 2012-3-5,15:49:59
 * @Description MinaClient类
 */
public class MinaClient extends IoHandlerAdapter {

    private static final Logger log = LogManager.getLogger(MinaClient.class);
    private Random random = new Random(System.currentTimeMillis());

    public MinaClient() {
        IoConnector connector = new NioSocketConnector();
          DefaultIoFilterChainBuilder chain=connector.getFilterChain();
             chain.addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.NUL, LineDelimiter.NUL))); 
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        //connector.getFilterChain().addLast(
                //"codec",
                //new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 设置编码过滤器
        connector.setConnectTimeout(30);
        connector.setHandler(this);// 设置事件处理器
        ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
                2009));// 建立连接
        cf.awaitUninterruptibly();// 等待连接创建完成
//        cf.getSession().write("hello");// 发送消息
//        cf.getSession().write("quit");// 发送消息
//        cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开
        cf.addListener(new IoFutureListener<ConnectFuture>() {

            @Override
            public void operationComplete(ConnectFuture future) {
                IoSession session = future.getSession();
                while (!session.isClosing()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String message = "你好,我roll了" + random.nextInt(100) + "点.";
                    session.write((Object)message);
                }
            }
        });
        connector.dispose();
    }

    public void operationComplete(ConnectFuture future) {
        IoSession session = future.getSession();
        while (!session.isClosing()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String message = "你好,我roll了" + random.nextInt(100) + "点.";
            session.write(message);
        }
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        System.out.println("批复:" + message.toString());
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        System.out.println("报告:" + message.toString());
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        session.close(true);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new MinaClient();
        }
    }
}
